<template>
  <div>
    <span v-for="(operation, index) in operations" :key="index">
      <slot :name="operation.action" :operation="operation">
        <el-button
          :type="row | operationTypeFilter(operation)"
          size="mini"
          @click="handleOperation({ operation, row, column })"
        >
          {{ row | operationNameFilter(operation) }}
        </el-button>
      </slot>
    </span>
  </div>
</template>

<script>
export default {
  name: 'TableOperation',
  filters: {
    // 选项名过滤
    operationNameFilter(row, operation) {
      if (operation.action === 'toggle') {
        // toggle操作 显示值不一样的label
        for (const option in operation.options) {
          if (row[operation.field] !== undefined) {
            if (!operation.options.hasOwnProperty(option)) continue
            if (operation.options[option].label) {
              if (operation.options[option].value !== row[operation.field]) {
                return operation.options[option].label
              }
            } else {
              if (option.toString() !== row[operation.field].toString()) {
                return operation.options[option]
              }
            }
          }
        }
      } else if (operation.label) {
        // 有传label直接显示
        return operation.label
      } else {
        // 没传label 显示默认值
        switch (operation.action) {
          case 'edit':
            return '编辑'
          case 'delete':
            return '删除'
          default:
            return ''
        }
      }
    },
    // 选项类型过滤
    operationTypeFilter(row, operation) {
      if (operation.types) {
        // 有types 优先选用types的值
        for (const key in operation.types) {
          if (row[operation.field] !== undefined) {
            if (key.toString() === row[operation.field].toString()) {
              return operation.types[key]
            }
          }
        }
      } else if (operation.type) {
        // 有type使用type
        return operation.type
      } else {
        // types和type都没有 使用默认值
        switch (operation.action) {
          case 'delete':
            return 'danger'
          case 'toggle':
            return 'primary'
          default:
            return 'primary'
        }
      }
    }
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['operations', 'row', 'column', 'form'],
  methods: {
    handleOperation({ operation, row, column }) {
      this.$emit('handle-operation', { operation, row, column })
    }
  }
}
</script>

<style scoped>
  ul,li {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }
</style>
